package vn.ebuzz.sms.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import vn.ebuzz.sms.core.Database;

public class RetrieveServlet extends HttpServlet {
	private static Logger log = Logger.getLogger("retrieve");


	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		// TODO Auto-generated method stub
		String codes = req.getParameter("codes");
		PrintWriter out = resp.getWriter();
		if(codes==null||codes.length()==0){
			out.print("1|MISSING CODES");
			return;
		}


		Update  t= new Update(codes);
		new Thread(t). start ();
		out.print("0|UPDATE SUCCESS");
	}
	public void UpdateMO(String code){
		Connection conn = Database.getConnection();
		Statement st = null;

		try{
			st = conn.createStatement();
		    st.executeUpdate("update incoming set status = 0 where upper(message) like '%"+code.toUpperCase()+"%' and status = 2");

		} catch(Exception e){
			log.error("Error", e);
		} finally{

			if(st != null)
				try {
					st.close();
				} catch (SQLException e) {
					log.error("Error", e);
				}
				Database.closeConnection(conn);					
		}
	}
	private class Update implements Runnable{
		private String str = "";
		public Update(String codes) {
			str = codes;
			// TODO Auto-generated constructor stub
		}

		public void run() {
			// TODO Auto-generated method stub
			String[] listCodes = str.split(";");
			for(String item:listCodes){
				UpdateMO(item);
			}
		}

	}
}
